package com.huaxin.hxmoduleworkorder.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.hxmoduleworkorder.dto.request.InspectionOrderCabinetCreateReqDTO;
import com.huaxin.hxmoduleworkorder.mapper.InspectionOrderCabinetMapper;
import com.huaxin.hxmoduleworkorder.mapping.InspectionOrderCabinetMapping;
import com.huaxin.hxmoduleworkorder.models.InspectionOrderCabinet;
import com.huaxin.hxmoduleworkorder.service.InspectionOrderCabinetService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class InspectionOrderCabinetServiceImpl extends ServiceImpl<InspectionOrderCabinetMapper, InspectionOrderCabinet> implements InspectionOrderCabinetService {

    private final InspectionOrderCabinetMapping inspectionOrderCabinetMapping;

    /**
     * 创建巡查工单配电箱关联
     *
     * @param in 创建参数
     * @return 创建结果
     */
    @Override
    public Boolean create(InspectionOrderCabinetCreateReqDTO in) {
        if (in == null) {
            return false;
        }
        if (StringUtils.isBlank(in.getOrderId())) {
            return false;
        }
        if (StringUtils.isBlank(in.getCabinetId())) {
            return false;
        }
        InspectionOrderCabinet entity = inspectionOrderCabinetMapping.toEntity(in);
        return save(entity);
    }

    /**
     * 批量创建巡查工单配电箱关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchCreate(List<InspectionOrderCabinetCreateReqDTO> in) {
        if (in == null || in.isEmpty()) {
            return false;
        }

        // 如果工单ID或者配电箱ID为空，则返回false
        if (in.stream().anyMatch(item -> StringUtils.isBlank(item.getOrderId()) || StringUtils.isBlank(item.getCabinetId()))) {
            return false;
        }

        // 去除重复数据
        in = in.stream().distinct().collect(Collectors.toList());

        List<InspectionOrderCabinet> entityList = inspectionOrderCabinetMapping.toEntityList(in);
        return this.saveBatch(entityList);
    }

    /**
     * 删除巡查工单配电箱关联
     *
     * @param orderId   工单ID
     * @param cabinetId 配电箱ID
     * @return 删除结果
     */
    @Override
    public Boolean delete(String orderId, String cabinetId) {
        if (StringUtils.isBlank(orderId) || StringUtils.isBlank(cabinetId)) {
            return false;
        }
        return this.baseMapper.delete(orderId, cabinetId);
    }

    /**
     * 删除工单关联的工单配电箱
     *
     * @param orderId 工单ID
     * @return 删除结果
     */
    @Override
    public Boolean deleteByOrderId(String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return false;
        }
        return this.baseMapper.deleteByOrderId(orderId);
    }
}
